/**
 * 
 */
package com.pactera.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liuqs
 * @version
 * @since 2017年12月25日 下午3:44:17
 */
public class HttpClientUtil {

	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	
	public static String HttpGet(String url) {
		String result = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			
			logger.debug("executing request " + httpget.getURI());
			
			long beginTime = System.currentTimeMillis();
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			
			long endTime = System.currentTimeMillis();
			logger.debug("response times " +(endTime-beginTime));
			
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				logger.debug("--------------------------------------");
				// 打印响应状态
				logger.debug(response.getStatusLine().toString());
				if (entity != null) {
					// 打印响应内容长度
					logger.debug("Response content length: " + entity.getContentLength());
					// 打印响应内容
					result = EntityUtils.toString(entity);
					logger.debug("Response content: " + result);
				}
				logger.debug("------------------------------------");
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	
	public static String HttpPost(String url,Map< String, String> params) {
		String result = null;
        // 创建默认的httpClient实例.    
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        // 创建httppost    
        HttpPost httppost = new HttpPost(url);  
        // 创建参数队列    
        List<BasicNameValuePair> formparams = new ArrayList<>();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			logger.debug("key= " + entry.getKey() + " and value= " + entry.getValue());
			formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
		}
        UrlEncodedFormEntity uefEntity;  
        try {  
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
            httppost.setEntity(uefEntity);
            logger.debug("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);  
            try {  
                HttpEntity entity = response.getEntity();  
                if (entity != null) {
                	result = EntityUtils.toString(entity, "UTF-8");
                	logger.debug("--------------------------------------");
                	logger.debug("Response content: " + result);
                	logger.debug("--------------------------------------");
                    return result;
                }  
            } finally {  
                response.close();  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        } 
        return result;
    }
	
	public static String sendGet(String url,String param) {
        StringBuffer sb = new StringBuffer(); 
        BufferedReader in = null;
        try {
        	String urlStr = url + "?" + param;
            URL realUrl = new URL(urlStr);
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept","*/*");
            connection.setRequestProperty("connection","Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/57.0");
            // 建立实际的连接
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));  
            String line = "";  
            while ((line = in.readLine()) != null){  
            	sb.append(line);  
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return sb.toString();
    }
}
